package com.meng.Interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 登录拦截器  只拦截请求 个人认为用拦截器更好 因为不需要处理静态文件的请求
 *
 * 拦截器是 AOP的一种实现 利用和是代理模式 注：代理模式和回调的区别  回调没有实现多态,代理有多态的实现
 *
 * @author MENG
 * @version 2017/12/22
 * @see
 */
@Component
public class LoginAndLogoutInterceptor implements HandlerInterceptor
{

    /**
     * 请求执行之前
     *
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object o)
        throws Exception
    {
        HttpSession session = request.getSession();

        System.out.println(session.getId());

        //用户已经登录
        if(session.getAttribute("user") != null)
        {
            return true;
        }

        //重定向登录页面
        response.sendRedirect("/toLogin");
        //不能使用重定向直接请求 认证中心的登录页面 需要使用window.location.href
        //不然 会使 session 共享失效
//        response.sendRedirect(loginUrl+"?requestUrl="+request.getRequestURL());


        return false;
    }

    /**
     * 请求执行之后
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView)
        throws Exception
    {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse, Object o, Exception e)
        throws Exception
    {

    }
}
